package com.hzit.cart.config;

import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 类名：
 * 作者：WF
 * 功能：openfeign请求发起时，此拦截器才会起作用！
 * 问题：openfeign在进行微服务调用时，会丢失请求头！下面是解决办法：就是在新的请求RequestTemplate中添加老请求的请求头信息！
 */
@Configuration
public class RequestInterceptorConfig {

	@Bean("requestInterceptor")
	public RequestInterceptor requestInterceptor(){
		return template -> {  //template: 新的请求对象，由openfeign定义的请求
			//1. 下面得到的是老的请求
			ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
			HttpServletRequest request = requestAttributes.getRequest();
			String cookie = request.getHeader("Cookie");
			System.out.println("cookie = " + cookie);
			template.header("Cookie",cookie);
		};
	}

}
